--[[
    desc: 看板娘更换、解锁界面
    author:Hoo
    time:2022-01-10 20:09:36
]]

--- @class UISide2D
local UISide2D = UIBase.New(PanelResNames.UISide2D)
local M = UISide2D

--- 板娘数据结构
--- @alias ItemStruct {id: number, name: string, imgUrl: string, useType: number, unlock: boolean, unlockDesc: string, unlockType: number, unlockParam: number}

--- 看板娘数据集合
--- @type ItemStruct[]
local mItemDatas = nil

--- 解锁板娘集合
--- @type number[]
local mUnlockList = nil

--- 当前选择的索引
--- @type number
local mSelectedIndex = nil

--- 点击事件时间戳（防连点）
--- @type number
local mClickTick = 0


--- 使用类型
local UserTypeEnum = {
    None   = 0,  -- 未使用
    Normal = 1,  -- 主线挂机
    Hard   = 2,  -- 唤魔之旅 
}
-- 板娘类型
local SideGirlType = {
    Normal = 1,  -- 主线挂机
    Hard   = 2,  -- 唤魔之旅
}
-- 解锁类型
local UnlockTypeEnum = {
    None = 0,    -- 直接投放
    Item = 1,    -- 道具解锁
}

function M.Init()
    UIBase.Init(M)
end

--- @protected
function M:OnCreate()
    -- 看板娘列表
    self.listItem = self:GetChild("n3")
    self:SetDynamicList(self.listItem, self.listItemRenderer, self, false)

    --- 按钮类型控制器
    --- @type GController
    self.ctrlBtnType = self:GetController("type")

    -- 解锁道具消耗
    self.imgUnlockIcon = self:GetChild("img_coin")
    self.txtUnlockNum  = self:GetChild("text_num")
    self.ctrlNum       = self:GetController("num")
    self.ctrlLockType  = self:GetController("locktype")

    -- 道具来源界面
    self.sourceUIobj          = self:GetChild("UISourceMultiple");
    self.showSourceController = self:GetController("showSource")

    self.listItem.onClickItem:Add(self.onEventClickListItem, self)
    self:RegisterOnClick(self:GetChild("btnchangeguaji"),  self.onClickChangeNormalStage, self)
    self:RegisterOnClick(self:GetChild("btnchangehuanmo"), self.onClickChangeHardStage,   self)
    self:RegisterOnClick(self:GetChild("btn_jiesuo"),      self.onClickUnlock,            self)
    self:RegisterOnClick(self:GetChild("btnunlock"),       self.onClickUnlockHelp,        self)
    self:RegisterOnClick(self:GetChild("btnSource"),       self.onClickSourceHelp,        self)
    self:RegisterOnClick(self:GetChild("bgClose"),         self.onClickClose,             self)

    ListenEvent(Config.EventType.SideGirlUnlockListRet , self.resUnlockRoleList,    self)
    ListenEvent(Config.EventType.SideGirlReplaceRet ,    self.resReplaceRole,       self)
    ListenEvent(Config.EventType.SideGirlUnlockRet ,     self.resUnlockRole,        self)
end
--- @protected
function M:OnEnable()
    self:initData()
    self:initUI()

    self:reqUnlockRoleList()
end
--- @protected
function M:OnDisable()
end
--- @protected
function M:OnDestroy()
    mItemDatas     = nil
    mUnlockList    = nil
    mSelectedIndex = nil

    self.listItem.onClickItem:Clear()
    CloseEvent(Config.EventType.SideGirlUnlockListRet , self.resUnlockRoleList,    self)
    CloseEvent(Config.EventType.SideGirlReplaceRet ,    self.resReplaceRole,       self)
    CloseEvent(Config.EventType.SideGirlUnlockRet ,     self.resUnlockRole,        self)
end

--- 初始化数据
--- @private
function M:initData()
    mClickTick     = 0
    mSelectedIndex = 1
    mItemDatas     = {}

    local tableData = dataTable.getDataTable("t_sidegirl")
    for _, data in pairs(tableData) do
        --- @type ItemStruct
        local itemData = {}
        itemData.id          = tonumber(data.f_MainGirlId)
        itemData.name        = data.f_MainGirlName
        itemData.imgUrl      = data.f_ImgPath
        itemData.unlockDesc  = data.f_UnlockDesc
        itemData.unlockType  = data.f_UnlockType
        itemData.unlockParam = data.f_UnlockParameter
        itemData.useType     = 0
        itemData.unlock      = false
        table.insert(mItemDatas, itemData)
    end

    table.sort(mItemDatas, function(v1, v2)
        return v1.id < v2.id
    end)
end
--- 刷新数据
--- @private
function M:refreshData()
    local normalId, hardId = HeroManager.getShowFemaleRole(), HeroManager.getShowTravelFemaleRole()
    for index, data in ipairs(mItemDatas) do
        if data.id == normalId then
            data.useType = UserTypeEnum.Normal
        elseif data.id == hardId then
            data.useType = UserTypeEnum.Hard
        else
            data.useType = UserTypeEnum.None
        end
        if table.contains(mUnlockList, data.id) then
            data.unlock = true
        end
    end
end

--- 初始化UI
--- @private
function M:initUI()
    
end
--- 刷新数据
--- @private
function M:refreshUI()
    self.listItem.numItems = #mItemDatas
    self:refreshButtonState()
    self:refreshCostView()
end

--- 刷新按钮状态
--- @private
function M:refreshButtonState()
    local normalId, hardId = HeroManager.getShowFemaleRole(), HeroManager.getShowTravelFemaleRole()
    local currData = mItemDatas[mSelectedIndex]
    if currData and currData.unlock then
        if currData.id == normalId --[[--冒险]] then
            self.ctrlBtnType.selectedIndex = 2
        elseif currData.id == hardId --[[--唤魔]] then
            self.ctrlBtnType.selectedIndex = 3
        else
            self.ctrlBtnType.selectedIndex = 1
        end
    else
        self.ctrlBtnType.selectedIndex = 0
    end
end

--- 刷新消耗面板
--- @private
function M:refreshCostView()
    local currData = mItemDatas[mSelectedIndex]
    if not currData or currData.unlock then
        return
    end

    local costId, costNum  = currData.unlockParam, 1
    local currNum = logicMgr.ItemManager.getItemCountbyModelId(costId)
    self.imgUnlockIcon.url = EnumConst.AtlasPath.ItemAtlas .. logicMgr.ItemManager.GetItemIcon(costId)
    self.txtUnlockNum.text = string.format("%d/%d", currNum, costNum)
    self.ctrlNum.selectedIndex = currNum >= costNum and 1 or 0
    
    if currData.unlockType == UnlockTypeEnum.Item then
        self.ctrlLockType.selectedIndex = 0
    else
        self.ctrlLockType.selectedIndex = 1
    end
end

--- 列表item
--- @private
--- @param index number  索引
--- @param obj   GObject 板娘item对象
function M:listItemRenderer(index, obj)
    local data = mItemDatas[index]

    local comRole    = obj:GetChild("img")
    local imgRole    = comRole:GetChild("img")
    local txtName    = obj:GetChild("text_name")
    local ctrlUse    = obj:GetController("use")
    local ctrlChoose = obj:GetController("choose")
    local ctrlUnlock = comRole:GetController("unlock")

    imgRole.url  = data.imgUrl
    txtName.text = getLanguage(data.name)
    ctrlUse.selectedIndex    = data.useType
    ctrlUnlock.selectedIndex = data.unlock and 1 or 0
    ctrlChoose.selectedIndex = mSelectedIndex == index and 1 or 0
end

function M:onEventClickListItem(evt)
    local currItem = evt.data
    local index = self.listItem:GetChildIndex(currItem) + 1
    local data  = mItemDatas[index]

    local lastItem = self.listItem:GetChildAt(mSelectedIndex - 1)
    if lastItem then
        lastItem:GetController("choose").selectedIndex = 0
    end

    mSelectedIndex = index
    currItem:GetController("choose").selectedIndex = 1
    self:refreshButtonState()
    self:refreshCostView()
end

--- 更换看板娘（主线冒险）
--- @private
function M:onClickChangeNormalStage()
    if self.ctrlBtnType.selectedIndex == 2 then
        UISysTips.AddMsg(getLanguage("SideGrilFail"))
        return
    end

    local data = mItemDatas[mSelectedIndex]
    self:reqReplaceRole(SideGirlType.Normal, data.id)
end

--- 更换看板娘（唤魔之旅）
--- @private
function M:onClickChangeHardStage()
    if self.ctrlBtnType.selectedIndex == 3 then
        UISysTips.AddMsg(getLanguage("SideGrilFail"))
        return
    end

    local data = mItemDatas[mSelectedIndex]
    self:reqReplaceRole(SideGirlType.Hard, data.id)
end

--- 查看解锁途径
--- @private
function M:onClickUnlock()
    if self.ctrlNum.selectedIndex == 0 then
        UISysTips.AddMsg(getLanguage("SideGrilUnlockFail"))
        return
    end

    local currTick = HelperFunc.GetServerTime()
    if currTick - mClickTick <= 1 then
        return
    end
    mClickTick = currTick

    local data = mItemDatas[mSelectedIndex]
    self:reqUnlockRole(data.id)
end
--- 查看解锁途径
--- @private
function M:onClickUnlockHelp()
    local data = mItemDatas[mSelectedIndex]
    if data == nil then
        return
    end

    UICommonPop.Init(121, function() end, getLanguage(data.unlockDesc))
end

--- 查看解锁道具来源
--- @private
function M:onClickSourceHelp()
    local data = mItemDatas[mSelectedIndex]
    if data == nil then
        return
    end

    self.showSourceController.selectedIndex = 1
    self.showSourceList = { data.unlockParam }
    self:updateSource()
end
function M:updateSource()
    local that = self
    logicMgr.ItemManager.updateSourceUI(
        that.sourceUIobj, 
        that.showSourceList, 
        function()
            that.showSourceController.selectedIndex = 0;
        end, 
        function()
            that.showSourceController.selectedIndex = 0;
            that:onClickClose()
        end
    );
end

--- 关闭界面
--- @private
function M:onClickClose()
    closeUI(PanelResNames.UISide2D)
end

-----------------------------------------------------------------------
--- 网络交互
-----------------------------------------------------------------------
--- 请求板娘解锁列表
--- @private
function M:reqUnlockRoleList()
    heroLinkHandler.ReqUnlockFemaleRole()
end
--- @param data number[] 解锁列表
function M:resUnlockRoleList(data)
    mUnlockList = data

    self:refreshData()
    self:refreshUI()
end

--- 更换
--- @private
--- @param type   number 板娘类型
--- @param heroId number 板娘id
function M:reqReplaceRole(type, heroId)
    heroLinkHandler.ReqReplaceFemaleRole(type, heroId)
end
--- @param data ResReplaceFemaleRoleMessage
function M:resReplaceRole(data)
    HeroManager.setShowFemaleRole(data.showFemaleRole)
    HeroManager.setShowTravelFemaleRole(data.showTravelFemaleRole)

    -- 刷新
    self:refreshData()
    self:refreshUI()

    -- 更换成功提示
    UISysTips.AddMsg(getLanguage("SideGirlPop"))
end

--- 解锁
--- @private
--- @param roleId number 板娘id
function M:reqUnlockRole(roleId)
    heroLinkHandler.ReqOpenFemaleRole(roleId)
end
--- @param data number 板娘id
function M:resUnlockRole(data)
    table.insert(mUnlockList, data)

    self:refreshData()
    self:refreshUI()
    UISysTips.AddMsg(getLanguage("SideGrilUnlockSuccess"))
end
return M
